package com.iwayin.web.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.json.JSONObject;

import com.iwayin.core.common.Constants;
import com.iwayin.core.dao.user.UserDAO;
import com.iwayin.core.dataobject.UserDO;
import com.iwayin.web.common.CookieUtil;
import com.iwayin.web.common.ThreadLocalManager;
import com.iwayin.web.common.WebConstants;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 
 * @author LIUWENLONG
 * 
 */
public class SessionUserInterceptor extends AbstractInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3701993154537960063L;

	private UserDAO userDAO;

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		Map session = invocation.getInvocationContext().getSession();
		UserDO user = (UserDO) session.get(WebConstants.LOGIN_USER);
		if (user == null) {
			user = login();
		}
		if (user != null) {
			session.put(WebConstants.LOGIN_USER, user);
			ThreadLocalManager.setLoginUser(user);
			invocation.getInvocationContext().put("jsonUser", new JSONObject(user));
		}
		return invocation.invoke();
	}

	private UserDO login() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String username = CookieUtil.getCookieValueByName(request, Constants.COOKIE_USERNAME);
		String password = CookieUtil.getCookieValueByName(request, Constants.COOKIE_PASSWORD);
		UserDO user = userDAO.getUserByNickName(username);
		if (user != null) {
			if (user.getLoginPwd().equals(password)) {
				return user;
			}
		}
		return null;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}
}
